package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet(name = "RegisterServlet", urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        // 校验用户名唯一
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement check = conn.prepareStatement("SELECT id FROM users WHERE username=?")) {
            check.setString(1, username);
            try (ResultSet rs = check.executeQuery()) {
                if (rs.next()) {
                    req.setAttribute("error", "用户名已存在");
                    req.getRequestDispatcher("register.jsp").forward(req, resp);
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 插入新用户
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement("INSERT INTO users(username, password, phone, address, status, is_admin) VALUES (?, ?, ?, ?, ?, false)")) {
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, phone);
            ps.setString(4, address);
            ps.setString(5, "待审核");
            ps.executeUpdate();
            resp.sendRedirect("login.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "注册失败，请重试");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("register.jsp").forward(req, resp);
    }
} 